<template>
  <div class="page-list-live">
    <PageList>
      <template #header>车辆管理</template>
      <template #filter>
        <ListFilter :form="topFilter" @search="handleSearch" @reset="handleReset"></ListFilter>
      </template>
      <template #tips>
        <el-button icon="el-icon-delete" type="danger" @click="batchDeletion">批量删除</el-button>
        <el-button icon="el-icon-document-add" type="primary" @click="handleAdd">新增</el-button>
        <el-button icon="el-icon-folder-add" type="primary" @click="clickUpload">批量导入</el-button>
        <el-button icon="el-icon-folder-remove" type="primary" @click="handleOut">批量导出</el-button>
      </template>
      <template #table>
        <ListTable ref="RefListTable" :loading="tableLoading" :table-data="tableData" :table-col="tableCol" @selectChange="handleSelectionChange">
          <template slot="col1" slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              :loading="scope.row.loadingEdit"
              size="mini"
              style="margin-left: 0px; margin-right: 10px;"
              type="text"
              @click="handleRowEdit(scope.row)"
            >编辑</el-button>
            <el-button
              :loading="scope.row.loadingDel"
              size="mini"
              icon="el-icon-delete"
              style="color: red; margin-left: 0px; margin-right: 10px;"
              type="text"
              @click="handleRowDel(scope.row)"
            >删除</el-button>
          </template>
        </ListTable>
      </template>
    </PageList>
    <!-- 新增车辆组件 -->
    <VehicleManagement ref="VehicleManagement" @success="afterEditSuccess"></VehicleManagement>
    <uploadComponent ref="uploadComponent" @success="afterEditSuccess"></uploadComponent>
  </div>
</template>
<script>
  import listMixin from "@/mixins/list"
  import { getToken } from '@/utils/auth' // get token from cookie
  import { parseTime } from '@/utils'
  import { localhostUrl } from '@/utils/setUrl.js'
  import VehicleManagement from "./components/VehicleManagement"
  import ListFilter from "@/components/ListFilter"
  import uploadComponent from './components/uploadComponent'
  import { car } from "@/api/api"
  export default {
    components: {
      ListFilter,
      VehicleManagement,
      uploadComponent
    },
    mixins: [listMixin],
    data() {
      return {
        previousQuery: {},
        // 在职状态
        statusList: [],
        deleteList: {
          id: "",
        },
        // 查询字段
        topFilter: {
          rfid: { label: "RFID卡", placeholder: "请输入RFID卡" },
          responsibleMan: { label: "负责人", placeholder: "请输入负责人" },
          carType: { label: "车辆类型", placeholder: "请输入车辆类型" },
          plateNumber: { label: "车牌号", placeholder: "请输入车牌号" },
        },
        // 列表数据
        tableData: [],
        // 列表表头
        tableCol: [
          { type: 'selection' },
          { type: "index", label: "序号", width: "60px" },
          { prop: "rfid", label: "RFID" },
          { prop: "carType", label: "车辆类型" },
          { prop: "plateNumber", label: "车牌号" },
          { prop: "responsibleMan", label: "负责人" },
          { prop: "responsiblePhone", label: "负责人电话" },
          { label: "操作", custom: "col1" },
        ],
      }
    },
    methods: {
      // 批量删除
      batchDeletion() {
        if (!this.deleteList.id) {
          this.$message.warning('请选择要删除的数据！')
          return
        }
        this.$_delConfirm('选中车辆', () => {
          this.delRowReq(this.deleteList)
        })
      },
      // 选中事件
      handleSelectionChange(event) {
        if (event.length > 0) {
          let ary = []
          event.forEach(item => {
            ary.push(item.id)
          })
          if (ary.length > 1) {
            this.deleteList.id = ary.join(',')
          } else {
            this.deleteList.id = ary[0]
          }
        } else {
          this.deleteList.id = ''
        }
      },
      // 请求列表数据
      async getList(query) {
        this.tableLoading = true
        try {
          let obj = query || { pageIndex: 1, pageSize: 10, orderBy: 'createdTime', orderByAscent: false }
          this.previousQuery = obj
          const { data: { items: resData, count, pageIndex } } = await car("post", obj, false)
          this.tableData = []
          this.tableData = resData.map((item) => {
            item.loadingEdit = false
            item.loadingDel = false
            return item
          })
          this.$nextTick(() => {
            this.$refs["RefListTable"].update({ page: pageIndex, count })
            this.tableLoading = false
          })
        } catch (err) {
          this.tableLoading = false
          this.tableData = []
        }
      },
      async afterEditSuccess() {
        this.getList(this.serchObj)
      },
      // 导出
      async exportHandler() {
        try {
          let url = localhostUrl + '/Car/ExcelFile'
          let xhr = new XMLHttpRequest()
          xhr.open('post', url, true)
          xhr.setRequestHeader('content-type', 'application/json')
          xhr.setRequestHeader('Authorization', `Bearer ${getToken()}`)
          xhr.responseType = 'blob' // 返回类型blob  blob 存储着大量的二进制数据
          xhr.onload = function () {
            if (this.status === 200) {
              let blob = this.response
              let reader = new FileReader()
              reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
              reader.onload = function (e) {
                var a = document.createElement('a') // 转换完成，创建一个a标签用于下载
                a.download = parseTime(new Date().getTime(), '{y}-{m}-{d}') + '车辆列表' + '.xls'
                a.href = e.target.result
                document.body.appendChild(a) // 修复firefox中无法触发click
                a.click()
                document.body.removeChild(a)
              }
            }
          }
          xhr.send(JSON.stringify(Object.assign(this.previousQuery, { pageIndex: 1, pageSize: 1e9 }))) // 发送ajax请求
        } catch (err) {
          this.$message.error('导出失败！')
        }
      },
      // 批量导出
      handleOut() {
        this.exportHandler()
      },
      // 点击上传
      clickUpload() {
         let objData = {
          // 进入哪一个程序
          status: 'add',
        }
        this.$refs['uploadComponent'].setPageName('car')
        this.$refs['uploadComponent'].openOne(objData)
      },
      handleAdd() {
        let objData = {
          // 进入哪一个程序
          status: 'add',
          apiKey: {
            add: '/Car', // 添加
          }
        }
        this.$refs['VehicleManagement'].openOne(objData)
      },
      handleRowEdit(row) {
        let objData = {
          // 进入哪一个程序
          status: 'edit',
          // 源数据
          row: row,
          // 源id
          id: row.id,
          // 查询参数
          searchData: {
            url: '/Car/' + row.id,
            method: 'GET',
            params: null
          }
        }
        this.$refs['VehicleManagement'].openOne(objData)
      },
      async delRowReq(row) {
        try {
          const obj = { id: row.id, value: null }
          await car("delete", obj, true)
          row.loadingDel = false
          this.getList(this.serchObj)
          this.$message({
            type: "success",
            message: "删除成功",
          })
        } catch (err) {
          row.loadingDel = false
          this.$message({
            type: 'error',
            message: '删除失败'
          })
        }
      },
      handleRowDel(row) {
        row.loadingDel = true
        this.$_delConfirm(
          "该车辆",
          () => {
            this.delRowReq(row)
          },
          () => {
            row.loadingDel = false
          }
        )
      },
    },
  }
</script>

<style lang="scss" scoped></style>
